use crate::{CommandState, Connection, Handler, Metadata};
use std::{io::Error, sync::Arc};
use tokio::{net::TcpListener, sync::Mutex};

pub struct Server;

impl Server {
    pub async fn start() -> Result<(), Error> {
        let listener = TcpListener::bind("127.0.0.1:8080").await?;

        let db = Arc::new(Mutex::new(Metadata::default()));

        loop {
            let (socket, _) = listener.accept().await?;
            let db_clone = Arc::clone(&db);
            tokio::spawn(async move {
                let conn = Connection::new(socket);
                let mut handler = Handler::new(conn, db_clone);

                match handler.read_command().await {
                    Ok(CommandState::CommandEnd) => {
                        return;
                    }
                    Ok(CommandState::CommandProducePanding) => {}
                    Ok(CommandState::CommandConsumePanding) => {}
                    Ok(CommandState::CommandError) => {
                        return;
                    }
                    Err(_err) => {}
                }

                loop {
                    let _ = handler.read_message().await;
                }
            });
        }
    }
}
